import re
import time
from redis import StrictRedis
from flask import current_app, request, jsonify, session, g
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, SignatureExpired, \
    BadSignature
from ..models import User
from .. import db
from ..func.redis_conn import r_db
from response_code import RET



# def get_token_by_pwd(phone, password):
#     print(phone, password)
#     uuid = int(time.time() * 1000000)  # uuid暂时用时间戳替代
#     if not all([phone, password, uuid]):
#         return jsonify({"code": RET.PARAMERR, "message": "参数不完整"})
#     try:
#         user = User.query.filter_by(phone=phone).first()
#     except:
#         return jsonify({"code": RET.DBERR, 'message': '数据库错误'})
#     if not user:
#         return jsonify({"code": RET.NODATA, 'message': '用户不存在'})
#     if user.verify_password(password) == False or user.name != username:
#         return jsonify({"code": RET.USERERR, "message": "用户名或密码错误"})
#     # Token
#     expiration = current_app.config['ADMIN_TOKEN_EXPIRATION']
#     token = generate_auth_token(user.id, uuid, None, expiration)
#     t = {
#         "token": token.decode('ascii')
#     }
#     # 保存 token 到redis
#     name = current_app.config["REDIS_PREFIX"] + str(user.id) + "_" + str(uuid)
#     r_db.setex(name=name, value=token, time=expiration)
#     return t

#
# def get_token_by_code(phone, code):
#     print(phone, code)
#     uuid = int(time.time() * 1000000)  # uuid暂时用时间戳替代
#     if not all([phone, code, uuid]):
#         return jsonify({"code": RET.PARAMERR, "message": "参数不完整"})
#     try:
#         user = User.query.filter_by(phone=phone).first()
#     except:
#         return jsonify({"code": RET.DBERR, 'message': '数据库错误'})
#     if not user:
#         return jsonify({"code": RET.OK, 'message': '注册新用户',"user_status":1})
#
#     # Token
#     expiration = current_app.config['ADMIN_TOKEN_EXPIRATION']
#     token = generate_auth_token(user.id, uuid, None, expiration)
#     t = {
#         "token": token.decode('ascii')
#     }
#     # 保存 token 到redis
#     name = current_app.config["REDIS_PREFIX"] + str(user.id) + "_" + str(uuid)
#     r_db.setex(name=name, value=token, time=expiration)
#     return t

def get_token_by_pwd(user_id,uuid):
    # Token
    expiration = current_app.config['ADMIN_TOKEN_EXPIRATION']
    token = generate_auth_token(user_id, uuid, None, expiration)
    t = {
        "token": token.decode('ascii')
    }
    # 保存 token 到redis
    name = current_app.config["REDIS_PREFIX"] + str(user_id) + "_" + str(uuid)
    r_db.setex(name=name, value=token, time=expiration)
    return t

def get_token_by_code(user_id,uuid):
    # Token
    expiration = current_app.config['ADMIN_TOKEN_EXPIRATION']
    token = generate_auth_token(user_id, uuid, None, expiration)
    t = {
        "token": token.decode('ascii')
    }
    # 保存 token 到redis
    name = current_app.config["REDIS_PREFIX"] + str(user_id) + "_" + str(uuid)
    r_db.setex(name=name, value=token, time=expiration)
    return t

def get_token_info(token):
    """获取令牌信息"""
    s = Serializer(current_app.config['SECRET_KEY'])
    try:
        data = s.loads(token, return_header=True)
    except SignatureExpired:
        return jsonify(msg='token is expired', error_code=1003)
    except BadSignature:
        return jsonify(msg='token is invalid', error_code=1002)

    r = {
        'scope': data[0]['scope'],
        'create_at': data[1]['iat'],
        'expire_in': data[1]['exp'],
        'uid': data[0]['uid'],
        'uuid': data[0]['uuid']
    }
    return jsonify(r)


def generate_auth_token(uid, uuid, scope=None,
                        expiration=7200):
    """生成令牌"""
    s = Serializer(current_app.config['SECRET_KEY'],
                   expires_in=expiration)
    return s.dumps({
        'uid': uid,
        'uuid': uuid,
        'scope': scope
    })
